<template>
  <div class="container">
    <div class="main" :model="form">
      <!-- 左右两部分 左边相当于新建文章 右边相当于编辑文章-->
      <div class="left">
        <h2>发布新攻略</h2>
        <p>分享你的个人游记，让更多人看到哦！</p>
        <div class="form">
          <el-input placeholder="请输入标题" clearable style="margin-top:10px" v-model="form.title"></el-input>
          <!-- 富文本组件 -->
          <div class="edit">
            <el-form class="content" ref="form">
              <el-form-item>
                <vue-editor
                  v-model="form.content"
                  :useCustomImageHandler="true"
                  @image-added="imgUpload"
                  :editorToolbar="customToolbar"
                ></vue-editor>
              </el-form-item>
            </el-form>
          </div>
          <div class="choiceCity">
            <el-form class="search-form-content" label-width="70px">
              <el-form-item label="选择城市">
                <!-- fetch-suggestions 返回输入建议的方法 -->
                <!-- select 点击选中建议项时触发 -->
                <el-autocomplete
                  v-model="form.city"
                  :fetch-suggestions="travelSearch"
                  placeholder="请搜索游玩城市"
                  @select="handleTravelSelect"
                  class="el-autocomplete"
                ></el-autocomplete>
              </el-form-item>
            </el-form>
          </div>
          <div>
            <el-button type="primary" size="small" style="margin-right:20px" @click="onSubmit">发布</el-button>或者
            <span style="color:orange; cursor:pointer;" @click="toDraft">保存到草稿</span>
          </div>
        </div>
      </div>
      <div class="right">
        <p style="margin-bottom:10px">
          草稿箱
          <span style="margin-left:4px;font-size:18px">({{draftPost.length}})</span>
        </p>
        <div v-for="(item,index) in draftPost" :key="index" style="margin-bottom:6px">
          <div class="title" @click="editPost(item)">
            {{item.title}}
            <span class="iconfont icon-xiezi"></span>
          </div>
          <p style="color:#999;">{{item.date}}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 引入momentjs
import moment from "moment";
export default {
  data() {
    return {
      // 定义一个表单对象，存放表单数据
      form: {
        content: "",
        title: "",
        city: ""
      },
      //   清空标题
      // input: "",
      // 存放每一篇 草稿
      draftItem: {
        date: ""
      },
      // 存放草稿对象的数组
      draftPost: [],
      // 存放建议旅游城市列表
      travelCity: [],
      customToolbar: [
        ["bold", "italic", "underline"],
        [{ list: "ordered" }, { list: "bullet" }],
        ["image", "code-block"]
      ]
    };
  },
  mounted() {
    // 加载草稿箱数据
    this.toDraft();
  },
  methods: {
    travelSearch(value, cb) {
      // if (!value.trim()) return cb([]);
      this.$axios({
        url: "/airs/city",
        // 带上api文档中写的参数
        params: {
          name: value
        }
      }).then(res => {
        const { data } = res.data;
        this.travelCity = data.map(v => {
          v.value = v.name.replace();
          return v;
        });
        cb(this.travelCity);
        console.log(this.travelCity);
      });
    },
    // 目标城市下拉选择时触发
    handleTravelSelect(item) {
      this.form.city = item.value;
    },

    // 上传图片
    imgUpload(file, Editor, cursorLocation, resetUploader) {
      console.log("添加了图片");
      var formData = new FormData();
      // 根据api文档配置属性名  file 这个数据就可以作为data发送ajax请求
      //  第二个file表示我们要传的文件 第一个是api中传文件的参数
      formData.append("file", file);
      console.log(formData,999);
      

      this.$axios({
        url: "/upload",
        method:"post",
        data: formData,
        processData:false,
        contentType:false,
      })
        .then(res => {
          // 看我们自己的url是什么样子 在哪里
          console.log(res,999999999999999);
          console.log(response);
          
          // const { data } = res.data;
          // let url = this.$axios.defaults.baseURL + data.url; // Get url from response
          // // 在光标处插入图片 这里是将我们传到服务器，返回一个地址的图片放入编辑器
          // Editor.insertEmbed(cursorLocation, "image", url);
          // // 有一个必须要做的就是重置上传组件
          // resetUploader();
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 提交文章内容
    onSubmit() {
      console.log(this.form);
      this.$axios({
        url: "/posts",
        method: "post",
        data: this.form,
        headers: {
          // Bearer属于jwt的token标准 Bearer后要加空格隔开
          Authorization: "Bearer " + this.$store.state.user.userInfo.token
        }
      }).then(res => {
        console.log(res);
        // console.log(this.form);
        if (res.data.status === 0) {
          this.$message.success(`${res.data.message}`);
        }
        this.form = {};
      });
    },
    // 保存到草稿箱
    toDraft() {
      this.$axios({
        url: "/posts",
        method: "post",
        data: this.form,
        headers: {
          // Bearer属于jwt的token标准 Bearer后要加空格隔开
          Authorization: "Bearer " + this.$store.state.user.userInfo.token
        }
      }).then(res => {
        console.log(res);
        const { data } = res.data;
        this.draftPost.push(data);
        // 遍历数组 改变日期格式
        for(var i=0;i<this.draftPost;i++){
          this.getDate(this.draftPost[i].created_at);
        }
        this.form = {};
      });
    },
    //   转换日期格式的方法
    getDate(time) {
      let date = new Date(time);
      date = moment(date).format("YYYY-MM-DD");
      this.draftItem.date = date;
    },
    // 编辑草稿数据
    editPost(data) {
      // 将对象中的城市名取出 给form表单中的city
      data.city = data.city.name;
      this.form = data;
    }
  }
};
</script>

<style lang="less" scoped>
.container {
  width: 1000px;
  margin: 0 auto;
  padding: 20px 0;
  .main {
    position: relative;
    box-sizing: border-box;
    .left {
      width: 750px;
      h2 {
        font-weight: normal;
        font-size: 22px;
        margin-bottom: 10px;
      }
      p {
        font-size: 12px;
        color: #999;
        margin-top: 10px;
      }
      /deep/.ql-editor{
        min-height: 400px;
      }
    }
    .right {
      position: absolute;
      top: 0;
      right: 0;
      width: 200px;
      border: 1px solid #ddd;
      padding: 10px;
      .title {
        cursor: pointer;
        &:hover {
          color: orange;
          text-decoration: underline;
        }
      }
    }
  }
  .content {
    margin-bottom: 20px;
    margin-top: 20px;
  }
}
</style>